<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="showAddCateDialog"
          >添加分类</el-button
        >
      </div>
      <!-- 表格 -->
      <zk-table
        :expand-type="false"
        show-index
        border
        :show-row-hover="false"
        :selection-type="false"
        :data="cateList"
        :columns="catColumns"
      >
        <!--      是否有效-->
        <template slot="isok" slot-scope="scope">
          <span
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: #55a532"
          ></span>
          <span
            class="el-icon-error"
            v-if="scope.row.cat_deleted === true"
            style="color: #a71d5d"
          ></span>
        </template>
        <!--        排序-->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag size="mini" type="success" v-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-if="scope.row.cat_level === 2"
            >三级</el-tag
          >
        </template>
        <!--        操作-->
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="medium"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="medium"
            @click="delCate(scope)"
            >删除</el-button
          >
        </template>
      </zk-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!--    添加分类弹出框-->
    <el-dialog
      title="添加分类"
      :visible.sync="addCatDialogVisible"
      width="50%"
      @close="addCatDialogClose"
    >
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        :rules="addCateFormRoles"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- options 用来指定数据源-->
          <!-- props 用来指定配置对象 -->
          <el-cascader
            expand-trigger="hover"
            :options="parentCateList"
            v-model="selectedKeys"
            :props="casCaderProps"
            change-on-select
            @change="parentCateChanged"
            popper-class="listbox"
            clearable
          >
          </el-cascader>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="addCatDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="AddCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类弹窗 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
    >
      <el-form
        :model="editCateInfo"
        ref="editCateInfoRef"
        :rules="editCateFormRoles"
        label-width="180px"
      >
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="editCateInfo.cat_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询条件
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      cateList: [],
      // 总数居条数
      total: 0,
      // 为table指定列的定义
      catColumns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前列使用的模板名称
          template: 'isok'
        },
        {
          label: '排序',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前列使用的模板名称
          template: 'order'
        },
        {
          label: '操作',
          // 表示将当前列定义为模板列
          type: 'template',
          // 表示当前列使用的模板名称
          template: 'opt',
          minWidth: '150px'
        }
      ],
      // 控制添加分类对话框显示与隐藏
      addCatDialogVisible: false,
      // 控制修改分类对话框显示与隐藏
      editCateDialogVisible: false,
      parentCateList: [],
      addCateForm: {
        // 将要添加的分类名称
        cat_name: '',
        // 父级分类id
        cat_pid: 0,
        // 默认添加的是一级分类，分类等级 0:一级 1：二级 2：三级
        cat_level: 0
      },
      // 指定级联选择器的配置对象
      casCaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      // 选中的父级分类的ID 数组
      selectedKeys: [],
      // 将要添加的分类 验证规则对象
      addCateFormRoles: {
        cat_name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' }
        ]
      },
      editCateFormRoles: {
        cat_name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' }
        ]
      },
      editCateInfo: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // this.$message.success(res.meta.msg)
      this.cateList = res.data.result
      this.total = res.data.total
      // console.log(res.data)
    },
    // 监听pagesize事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    // 点击按钮展示添加分类的对话框
    showAddCateDialog() {
      // 先获取腹肌分类的数据列表对话框
      this.getParentCateList()
      this.addCatDialogVisible = true
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res.data)

      this.parentCateList = res.data
    },
    // 选择项发生变化
    parentCateChanged() {
      // console.warn(this.selectedKeys)
      if (this.selectedKeys.length > 0) {
        // 父级分类id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      }
    },
    // 添加分类弹出框关闭事件
    addCatDialogClose() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedKeys = []
      this.addCatDialogVisible = false
    },
    // 点击按钮添加新的分类
    AddCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getCateList()
        this.addCatDialogClose()
      })
    },
    editCate(scope) {
      this.getCateById(scope.cat_id)
      this.editCateDialogVisible = true
      console.log('编辑', this.editCateInfo)
    },
    async getCateById(id) {
      const { data: res } = await this.$http.get('categories/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editCateInfo = res.data
    },
    async saveEditCate() {
      console.log(this.editCateInfo)
      const { data: res } = await this.$http.put(
        'categories/' + this.editCateInfo.cat_id,
        { cat_name: this.editCateInfo.cat_name }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.editCateInfo = res.data
      this.editCateDialogVisible = false
      this.getCateList()
    },
    delCate(scope) {
      this.$confirm('确认要删除该分类吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delCateFrom(scope.row.cat_id)
        })
        .catch(() => {
          console.log('cancel')
        })
    },
    async delCateFrom(id) {
      await this.$http
        .delete('categories/' + id)
        .then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error(res.data.meta.msg)
          }
          this.$message.success(res.data.meta.msg)
          // console.log(res)
          this.getCateList()
        })
        .catch(err => {
          console.error(err)
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-pagination {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
